<template>
  <div class="container">
    <h1 class="title">我的基金组合</h1>

    <p style="margin-bottom: 12px;">共 {{ total }} 个组合</p>

    <el-alert v-if="selectedFunds.length > 0" type="info" show-icon :title="`已选中 ${selectedFunds.length} 只基金`"
      style="margin-bottom: 12px;" />

    <el-table :data="portfolios" border row-key="id" style="width: 100%" :expand-row-keys="expandedRows"
      @expand-change="loadPortfolioFunds">
      <el-table-column type="expand">
        <template #default="props">
          <el-table :ref="el => fundTableRefs[props.row.id] = el" :data="props.row.funds || []" size="small" border
            :row-key="fund => fund.code" @selection-change="selection => handleSelectionChange(selection, props.row)"
            @row-click="(row) => toggleRowSelection(row, props.row)">
            <el-table-column type="selection" width="50" />
            <el-table-column prop="code" label="基金代码" width="120" />
            <el-table-column prop="name" label="基金名称" />
            <el-table-column prop="type" label="类型" />
            <el-table-column prop="companyName" label="基金公司" />
            <el-table-column prop="latestNav" label="最新净值" />
            <el-table-column prop="latestNavDate" label="净值日期" />
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <div style="display: flex; gap: 8px;">
                  <el-button size="small" type="success" plain @click.stop="viewProfile(scope.row)">
                    查看画像
                  </el-button>
                  <el-button size="small" type="warning" plain
                    @click.stop="removeFundFromPortfolio(props.row.id, scope.row.code)">
                    移除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>

      <el-table-column prop="name" label="组合名称" width="200" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="140">
        <template #default="scope">
          <el-popconfirm title="确定删除该组合？" confirm-button-text="确定" cancel-button-text="取消"
            @confirm="deletePortfolio(scope.row.id)" width="160">
            <template #reference>
              <el-button type="primary" plain size="small">
                <el-icon>
                  <Delete />
                </el-icon>
                删除组合
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top: 20px; display: flex; justify-content: flex-start;">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20]"
        :total="total" layout="total, sizes, prev, pager, next, jumper" background @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 基金画像弹窗 -->
    <el-dialog v-model="profileDialogVisible" :title="dialogFundProfile?.basicInfo?.name + ' 的基金画像'" width="1050px">
      <div v-if="dialogFundProfile" class="profile-container">
        <el-card shadow="hover" class="profile-card">
          <template #header><el-tag type="info">产品基本信息</el-tag></template>
          <el-descriptions :column="2" size="small" border>
            <el-descriptions-item label="基金名称">{{ dialogFundProfile.basicInfo.name }}</el-descriptions-item>
            <el-descriptions-item label="基金代码">{{ dialogFundProfile.basicInfo.code }}</el-descriptions-item>
            <el-descriptions-item label="基金类型">{{ dialogFundProfile.basicInfo.type }}</el-descriptions-item>
            <el-descriptions-item label="基金公司">{{ dialogFundProfile.basicInfo.companyName }}</el-descriptions-item>
            <el-descriptions-item label="基金经理">{{ dialogFundProfile.basicInfo.managerName }}</el-descriptions-item>
            <el-descriptions-item label="最新净值">
              {{ dialogFundProfile.basicInfo.latestNav }}（{{ dialogFundProfile.basicInfo.latestNavDate }}）
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card shadow="hover" class="profile-card">
          <template #header><el-tag type="info">基金标签</el-tag></template>
          <div>
            <el-tag v-for="tag in dialogFundProfile.tags" :key="tag" type="success" style="margin: 5px;">
              {{ tag }}
            </el-tag>
          </div>
        </el-card>

        <el-card shadow="hover" class="profile-card">
          <template #header><el-tag type="success">业绩表现</el-tag></template>
          <el-descriptions :column="2" size="small" border>
            <el-descriptions-item label="年化收益率">
              {{ (dialogFundProfile.performance.annualReturn * 100).toFixed(2) }}%
            </el-descriptions-item>
            <el-descriptions-item label="最大回撤">
              {{ (dialogFundProfile.performance.maxDrawdown * 100).toFixed(2) }}%
            </el-descriptions-item>
            <el-descriptions-item label="夏普比率">
              {{ dialogFundProfile.performance.sharpeRatio?.toFixed(2) }}
            </el-descriptions-item>
            <el-descriptions-item label="波动率">
              {{ dialogFundProfile.performance.stddev?.toFixed(4) }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card shadow="hover" class="profile-card">
          <template #header><el-tag type="warning">持仓分析</el-tag></template>
          <el-table :data="dialogFundProfile.holdings" border size="small">
            <el-table-column prop="stockName" label="股票名称" />
            <el-table-column prop="holdingRatio" label="占比（%）">
              <template #default="scope">
                {{ (scope.row.holdingRatio * 100).toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <el-card shadow="hover" class="profile-card">
          <template #header><el-tag type="primary">基金公告</el-tag></template>
          <p>{{ dialogFundProfile.announcementContent }}</p>
        </el-card>
      </div>

      <template #footer>
        <el-button @click="profileDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

import {
  getPortfoliosByPage,
  getPortfolioItems,
  getFundsByCodes,
  removeFundFromPortfolio,
  deletePortfolio
} from '../../api/fundApi'


const router = useRouter()

const portfolios = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const expandedRows = ref([])
const fundTableRefs = ref({})
const selectedFunds = ref([])
const selections = ref({})
const userId = 1

onMounted(() => {
  fetchPortfolios()
})

const fetchPortfolios = async () => {
  const res = await getPortfoliosByPage({
    userId,
    page: currentPage.value,
    size: pageSize.value
  })
  portfolios.value = res.data.content
  total.value = res.data.totalElements
  expandedRows.value = []
}

const loadPortfolioFunds = async (row, expanded) => {
  if (expanded && !row.funds) {
    const res = await getPortfolioItems(row.id)
    const fundCodes = res.data.map(item => item.fundCode)
    if (fundCodes.length === 0) {
      row.funds = []
      return
    }
    const fundRes = await getFundsByCodes(fundCodes)
    row.funds = fundRes.data

    await nextTick()
    const tableRef = fundTableRefs.value[row.id]
    if (tableRef) {
      row.funds.forEach(fund => {
        if (selectedFunds.value.includes(fund.code)) {
          tableRef.toggleRowSelection(fund, true)
        }
      })
    }
  }
}

const toggleRowSelection = (row, portfolioRow) => {
  const tableRef = fundTableRefs.value[portfolioRow.id]
  if (tableRef) {
    tableRef.toggleRowSelection(row)
  }
}

const handleSelectionChange = (selection, portfolioRow) => {
  selections.value[portfolioRow.id] = selection.map(f => f.code)
  selectedFunds.value = Array.from(
      new Set(Object.values(selections.value).flat())
  )
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchPortfolios()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchPortfolios()
}

const viewProfile = async (row) => {
  router.push(`/fund-profile/${row.code}`)
}
</script>

<style scoped>
.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 40px;
}
.title {
  text-align: center;
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 20px;
}
.profile-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-top: 10px;
}
.profile-card {
  padding: 10px;
}
</style>
